package com.exampleyyy.demoyyy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.exampleyyy.demoyyy.JieKouService.OrderServiceJieKou;
import com.exampleyyy.demoyyy.JieKouShiTiYYY.OrderMapper;
import com.exampleyyy.demoyyy.ShiTiYYY.*;
import com.exampleyyy.demoyyy.common.BaseContext;
import com.exampleyyy.demoyyy.common.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderService extends ServiceImpl<OrderMapper, Orders> implements OrderServiceJieKou {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     */
    @Transactional
    public void submit(Orders orders) {
        // 获得当前用户id
        Long userId = BaseContext.getCurrentId();

        // 查询购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);

        if (shoppingCarts == null || shoppingCarts.isEmpty()) {
            throw new CustomException("购物车为空，不能下单");
        }

        // 查询用户信息
        User user = userService.getById(userId);

        // 查询地址信息
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null) {
            throw new CustomException("用户地址信息有误，不能下单");
        }

        // 生成订单号（假设使用雪花算法）
        long orderId = System.currentTimeMillis(); // 简化示例，实际可使用 IdWorker

        // 使用 AtomicInteger 累计总金额
        AtomicInteger amount = new AtomicInteger(0);

        // 组装订单明细信息
        List<OrderDetail> orderDetails = shoppingCarts.stream().map(item -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());

            // 累计总金额
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());

            return orderDetail;
        }).collect(Collectors.toList());

        // 组装订单数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get())); // 设置总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        // 插入订单数据
        this.save(orders);

        // 批量插入订单明细
        orderDetailService.saveBatch(orderDetails);

        // 清空购物车
        shoppingCartService.remove(wrapper);
    }

    /**
     * 订单派送
     * @param id 订单ID
     */
    @Override
    public void deliveryOrder(Long id) {
        Orders order = this.getById(id);
        if (order == null) {
            throw new CustomException("订单不存在");
        }

        // 只有待派送状态的订单才能进行派送操作
        if (!order.getStatus().equals(2)) {
            throw new CustomException("订单状态错误，无法派送");
        }

        order.setStatus(3); // 3表示已派送
        this.updateById(order);
    }

    /**
     * 完成订单
     * @param id 订单ID
     */
    @Override
    public void completeOrder(Long id) {
        Orders order = this.getById(id);
        if (order == null) {
            throw new CustomException("订单不存在");
        }

        // 只有已派送状态的订单才能完成
        if (!order.getStatus().equals(3)) {
            throw new CustomException("订单状态错误，无法完成");
        }

        order.setStatus(4); // 4表示已完成
        this.updateById(order);
    }

    /**
     * 取消订单
     * @param id 订单ID
     */
    @Override
    public void cancelOrder(Long id) {
        Orders order = this.getById(id);
        if (order == null) {
            throw new CustomException("订单不存在");
        }

        // 只有待付款或待派送状态的订单才能取消
        if (!order.getStatus().equals(1) && !order.getStatus().equals(2)) {
            throw new CustomException("订单状态错误，无法取消");
        }

        order.setStatus(5); // 5表示已取消
        this.updateById(order);
    }
    @Override
    public void reorder(Long orderId) throws CustomException {
        // 参数校验
        if (orderId == null || orderId <= 0) {
            throw new CustomException("无效的订单ID");
        }

        // 获取当前用户ID
        Long userId = BaseContext.getCurrentId();

        // 1. 查询原始订单
        Orders order = this.getById(orderId);
        if (order == null) {
            throw new CustomException("订单不存在");
        }

        // 2. 查询订单明细
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId, orderId);
        List<OrderDetail> orderDetails = orderDetailService.list(queryWrapper);
        if (orderDetails == null || orderDetails.isEmpty()) {
            throw new CustomException("订单明细为空");
        }

        // 3. 清空当前用户的购物车
        LambdaQueryWrapper<ShoppingCart> cartWrapper = new LambdaQueryWrapper<>();
        cartWrapper.eq(ShoppingCart::getUserId, userId);
        shoppingCartService.remove(cartWrapper);

        // 4. 将订单明细转换为购物车项并添加到购物车
        for (OrderDetail detail : orderDetails) {
            ShoppingCart cartItem = new ShoppingCart();
            cartItem.setUserId(userId);
            cartItem.setDishId(detail.getDishId());
            cartItem.setSetmealId(detail.getSetmealId());
            cartItem.setDishFlavor(detail.getDishFlavor());
            cartItem.setName(detail.getName());
            cartItem.setImage(detail.getImage());
            cartItem.setAmount(detail.getAmount());
            cartItem.setNumber(detail.getNumber());
            cartItem.setCreateTime(LocalDateTime.now());
            cartItem.setUpdateTime(LocalDateTime.now());

            shoppingCartService.save(cartItem);
        }
    }
}